const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
// 创建express实例
const app = express()
// cors 解决跨域问题
app.use(cors())
// parse application/x-www-form-urlencoded
// false - 值为数组或者字符串 true - 值为任意类型
app.use(bodyParser.urlencoded({extended: false}))
// parse application/json
app.use(bodyParser.json())
//处理错误中间件
app.use((req, res, next) => {
    // status 1 - 失败 0 - 成功
    res.cc = (err, code = 1) => {
        res.send({
            code,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})
const jwtConfig = require('./config/JwtConfig')
const {expressjwt: jwt} = require('express-jwt')
app.use(jwt({
    secret: jwtConfig.jwtSecretKey,
    algorithms: ['HS256']
}).unless({
    path: [/^\/api\//]
}))
const loginRouter = require('./router/LoginRouter')
app.use('/api', loginRouter)  // 以 /api 为前缀

// 对不符合joi规则的情况报错
const joi = require('joi')
app.use((req, res, next) => {
    if (err instanceof joi.ValidationError) return res.cc(err)
})

//开启服务
app.listen(3000, () => {
    console.log('localhost:3000服务已开启...')
})